package com.mjlf.t.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * @ClassName EchoServer
 * @auther mjlf
 * @Date 2019/6/20 16:48
 * @Description TODO
 */
public class EchoServer {
    private final int port;

    public EchoServer(int port){
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        int port = 8080;
        new EchoServer(port).start();
    }

    public void start() throws Exception{

        //3
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            //4 像服务中添加一个组
            b.group(group)

                    //5指定Channel
                    .channel(NioServerSocketChannel.class)

                    //6绑定Address
                    .localAddress(new InetSocketAddress(port))

                    //7添加EchoServerHandle 到 Channel 的 ChannelPipeline
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new EchoServerHandle());
                        }
                    });

            //8绑定到服务器，sync等待服务器关闭
            ChannelFuture f = b.bind().sync();

            System.out.println(EchoServer.class.getName() + " start and listen on " + f.channel().localAddress());
            //9关闭channel 和块， 知道它被关闭
            f.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }
    }
}
